#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
#include <sys/types.h>
#include <unistd.h>
#define BUFFERSIZE 1024
int main()
{
    char buffer[BUFFERSIZE];
    int pipefd[2] = {0};
    if (pipe(pipefd) == -1)
    {
        perror("pipe fail");
        return 1;
    }

    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork fail");
        return 1;
    }
    else if (pid == 0)
    {
        close(pipefd[1]);
        int con = 20;
        while (con--)
        {
            sleep(0.5);
            //buffer[0] = 0;
            ssize_t n = read(pipefd[0], buffer, BUFFERSIZE - 1);
            if (n == -1)
            {
                perror("read");
                return 1;
            }
            buffer[n] = 0;
            printf("i am child.i get message:%s\n", buffer);
	    fflush(stdout);
        }
        close(pipefd[0]);
    }
    else
    {
        close(pipefd[0]);
        int con = 10;
        while (con--)
        {
            sleep(3);
            //buffer[0] = 0;
            snprintf(buffer, sizeof(buffer), "i am father.mypid is %d", getpid());
            write(pipefd[1], buffer, strlen(buffer));
            printf("i am father .i send message:%s\n", buffer);
	    fflush(stdout);
        }
        close(pipefd[1]);
    }

    return 0;
}
